package cn.yunyichina.openapi.proxy.main;

import cn.yunyichina.openapi.proxy.config.HttpServerConfig;
import cn.yunyichina.openapi.proxy.http.HttpServerInitializer;
import cn.yunyichina.openapi.proxy.utils.ServiceUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 代理器
 *
 * @author zhangkewen
 */
public class NotifyApiApp {

    private static final Logger logger = LoggerFactory.getLogger(NotifyApiApp.class);

    public static void main(String[] args) throws Exception {
        // 初始化http服务端配置
        HttpServerConfig.getConfig().initHttpConfig();
        logger.info("初始化http服务端配置完成");

        // 初始化所有dubbo的消费者服务
        ServiceUtil.init();
        logger.info("初始化所有dubbo的消费者服务完成");

        // 开启http服务
        logger.info("开始开启http服务进行端口监听");
        httpServerStart();
    }

    /**
     * 启动http服务
     *
     * @throws Exception
     */
    public static void httpServerStart() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new HttpServerInitializer())
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            Channel ch = b.bind(HttpServerConfig.getConfig().getPort()).sync().channel();
            String httpstr;
            httpstr = "http";
            logger.info(httpstr + " 服务启动成功，绑定端口：" + HttpServerConfig.getConfig().getPort() + '.');
            logger.info("打开你的浏览器，输入以下网址 " + httpstr + "://localhost:" + HttpServerConfig.getConfig().getPort() + '/');
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            ServiceUtil.close();
        }
    }

}
